import { getOutpatientInformation } from '@/services/order/api';
import { addPatientInfo, editPatientInfo } from '@/services/patient/patientApi';
import { showMsg } from '@/utils/utils';
import { ModalForm, ProFormText } from "@ant-design/pro-form";
import ProTable, { ProColumns } from '@ant-design/pro-table';
import { Card, Col, FormInstance, Row, Tabs } from 'antd';
import { useEffect, useRef } from 'react';
import DetailBillingHistory from './DetailBillingHistory';
import DetailOrderHistory from './DetailOrderHistory';
import styles from './style.less';

const DetailModal = (props: DetailModalProps) => {

  const { open, onOpenChange, rowData } = props;

  const formRef = useRef<FormInstance>();

  const columns: ProColumns[] = [
    {
      title: '就诊流水号',
      dataIndex: 'visit_no',
      width: 100
    },
    {
      title: '病人ID',
      dataIndex: 'patient_id',
      width: 100
    },
    {
      title: '病案号',
      dataIndex: 'case_no',
      width: 100
    },
    {
      title: '病人姓名',
      dataIndex: 'patient_name',
      width: 100
    },
    {
      title: '就诊时间',
      dataIndex: 'visit_time',
      width: 100
    },
    {
      title: '挂号科室代码',
      dataIndex: 'visit_dept_code',
      width: 100
    },
    {
      title: '挂号科室名称',
      dataIndex: 'visit_dept_name',
      width: 100
    },
    {
      title: '费用代码',
      dataIndex: 'rate_type_code',
      width: 100
    },
    {
      title: '费别名称',
      dataIndex: 'rate_type_name',
      width: 100
    },
    {
      title: '卡类型代码',
      dataIndex: 'ic_card_type_code',
      width: 100
    },
    {
      title: '卡类型名称',
      dataIndex: 'ic_card_type_name',
      width: 100
    },
    {
      title: '就诊卡号',
      dataIndex: 'ic_card_no',
      width: 100
    },
    {
      title: '就诊类型代码',
      dataIndex: 'visit_type_code',
      width: 100
    },
    {
      title: '就诊类型名称',
      dataIndex: 'visit_type_name',
      width: 100
    },
    {
      title: '最后更新时间',
      dataIndex: 'modify_time',
      width: 100
    },
    {
      title: '预约医生工号',
      dataIndex: 'appt_doctor_code',
      width: 100
    },
    {
      title: '预约医生姓名',
      dataIndex: 'appt_doctor_name',
      width: 100
    },
    {
      title: '接诊医生工号',
      dataIndex: 'visit_doctor_code',
      width: 100
    },
    {
      title: '接诊医生姓名',
      dataIndex: 'visit_doctor_name',
      width: 100
    },
  ];

  useEffect(() => {
    if (rowData) {
      formRef.current?.setFieldsValue(rowData);
    }
  }, [rowData]);

  const formatDate = (date: Date) => {
    var y = date.getFullYear();
    var m = date.getMonth() + 1 as any;
    m = m < 10 ? '0' + m : m;
    var d = date.getDate() as any;
    d = d < 10 ? ('0' + d) : d;
    return y + '' + m + '' + d;
  };

  const save = async (values: FormType) => {
    try {
      if (rowData) {
        await editPatientInfo({ ...values, record_id: rowData.record_id });
        showMsg('修改成功', 'success');
      } else {
        await addPatientInfo({ ...values });
        showMsg('新增成功', 'success');
      }
      onOpenChange?.(false);
    } catch (reason: any) {
      showMsg(reason.data?.errmsg || '保存失败');
    }
  };

  return <>
    <ModalForm<FormType>
      title={false}
      width='50%'
      formRef={formRef}
      layout="horizontal"
      modalProps={{ okText: "保存", maskClosable: false, destroyOnClose: true, bodyStyle: { padding: '2px 0 12px 0' } }}
      onVisibleChange={onOpenChange}
      initialValues={{ ...rowData }}
      visible={open}
      labelAlign="right"
      onFinish={save}
    >
      <Tabs type="card" tabBarStyle={{ marginBottom: 6, padding: '0 2px' }} defaultActiveKey={'tab1'}>
        <Tabs.TabPane key="tab1" tab="患者详情" className={styles.patientInfo}>
          <Card title="1.患者信息" bordered={false}>
            <Row gutter={24}>
              <Col span={6}>
                <ProFormText label="身份证号" name="identity_no" labelCol={{ flex: '0 0 auto' }} fieldProps={{ readOnly: true }} />
              </Col>
              <Col span={6}>
                <ProFormText label="姓名" name="patient_name" labelCol={{ flex: '0 0 auto' }} fieldProps={{ readOnly: true }} />
              </Col>
              <Col span={6}>
                <ProFormText label="手机号" name="mobile" labelCol={{ flex: '0 0 auto' }} fieldProps={{ readOnly: true }} />
              </Col>
              <Col span={3}>
                <ProFormText label="积分" name="available_integral" labelCol={{ flex: '0 0 auto' }} readonly />
              </Col>
              <Col span={3}>
                <ProFormText label="等级" name="rank" labelCol={{ flex: '0 0 auto' }} readonly />
              </Col>
            </Row>
          </Card>
          <Card title="2.患者病例" bordered={false}>
            <ProTable
              bordered
              search={false}
              request={async (params) => {
                try {
                  let end_time = new Date() as any;
                  let start_time = new Date(end_time) as any;
                  start_time.setMonth(end_time.getMonth() - 6);
                  end_time = formatDate(end_time);
                  start_time = formatDate(start_time);
                  const res = await getOutpatientInformation({ start_time, end_time, patient_id: rowData?.patient_id, id_card_no: rowData?.ic_card_no });
                  return { success: true, data: res, total: res.length };
                } catch (reason: any) {
                  showMsg(reason?.data?.errmsg);
                }
                return { success: false, data: [] };
              }}
              options={false}
              columns={columns}
              toolBarRender={false}
              scroll={{ x: 'max-content' }}
            />
          </Card>
        </Tabs.TabPane>
        <Tabs.TabPane key="tab2" tab="订单历史">
          <DetailOrderHistory identity_no={rowData?.identity_no} patient_id={rowData?.patient_id} />
        </Tabs.TabPane>
        <Tabs.TabPane key="tab3" tab="计划账单历史">
          <DetailBillingHistory patient_id={rowData?.patient_id} />
        </Tabs.TabPane>
      </Tabs>
    </ModalForm >
  </>;
};

type FormType = Pick<PERMISSIONSAPI.SubDept, 'sub_dept_name' | 'address' | 'status' | 'manager_oper_id'>;

interface DetailModalProps {
  open: boolean,
  onOpenChange: (open: boolean) => void,
  rowData?: PATIENT.PatientInfo
}

export default DetailModal;
